package com.playcrab.adouban.service;

import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;

import org.json.JSONException;

import com.google.gdata.client.douban.DoubanService;
import com.google.gdata.data.douban.DoumailFeed;
import com.google.gdata.util.ServiceException;
import com.playcrab.adouban.util.Constants;
import com.playcrab.adouban.util.DoubanAPI;
import com.playcrab.adouban.util.PreferenceUtil;

import java.io.IOException;
import java.util.*;

//TODO check for thread-safety!!1 

public class CheckingService extends Service {

	private static final String LOG_TAG = "CheckingService";

    public static final int MESSAGE_NUM_LOAD = 10;
    public static final int STATUS_NUM_LOAD = 6;

    private List<Thread> threads = Collections.synchronizedList(new LinkedList<Thread>());
 

    @Override
    public void onCreate() {
        Log.v(LOG_TAG, "Service onCreate");
        super.onCreate();
     }

    @Override
    public void onStart(final Intent intent, int startId) {
        super.onStart(intent, startId);

        Log.v(LOG_TAG, "Started command: " + intent);
        try {
            String action = intent.getAction();
            if (Constants.ACTION_CHECK_UPDATES.equals(action))
                checkUpdates();
        } catch (Exception e) {
            Log.e(LOG_TAG, "Exception while checking updates", e);
            //TODO: Need to save that to show for user later...
        }
    	
       
    }
 
    private void checkUpdates() {
		// TODO Auto-generated method stub
		
	}

	/**
     * Check given content type for updates
     *
     * @param toUpdate   - ordinal of ContentToUpdate
     * @param syncronous
     */
    void doCheck(final int toUpdate, final Bundle updateParams, boolean syncronous) {
        if (syncronous) {
           // updateContent(toUpdate, updateParams);
        } else {
            Thread t = new Thread(new Runnable() {
                @Override
                public void run() {
                 //   updateContent(toUpdate, updateParams);
                }
            });
            threads.add(t);
            t.start();
        }
    }
    public boolean acessTokenIsValid() {
		SharedPreferences settings = getSharedPreferences(
				Constants.PREF_DOUBAN, 0);
		String requestToken = settings.getString(Constants.ACCESS_TOKEN,
				"false"); 
		if (requestToken.equals("false")   )
			return false;
		else
			return true;
	}
	
    public DoubanService getAuthedDoubanService() {

		DoubanService myService = DoubanAPI.getInstance().getService();
		SharedPreferences settings = getSharedPreferences(
				Constants.PREF_DOUBAN, 0);
		if(acessTokenIsValid()){
			String acessToken = settings.getString(Constants.ACCESS_TOKEN,
			"false");
			String acessTokenSecret = settings.getString(
					Constants.ACCESS_TOKEN_SECRET, "false");
			myService.setAccessToken(acessToken, acessTokenSecret);
			return myService;
		}else{ 
			return null;
		}

		
	}
	

    private void checkDoumailInboxUnread() throws IOException, ServiceException {
        Log.v(LOG_TAG, "Checking updates");
        
        DoubanService service = getAuthedDoubanService();
        if(service==null)
        	return;
        
        DoumailFeed feed = service.getDoumailInboxUnread(1, 20);
        int result = feed.getTotalResults(); 
        if(result>0){ 
	        if (  PreferenceUtil.getNotifications(getApplicationContext())) {
	  
	          //  UpdatesNotifier.notifyChangesHistory(getApplicationContext(), 1, newEvents);
	        }
        }
    }
 
    @Override
    public void onDestroy() {
        Log.v(LOG_TAG, "Service onDestroy");

        // TODO: stop all running threads
        for (Thread t : threads) {
            if (t.isAlive())
                t.interrupt();
        }
        super.onDestroy();
    }

	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return null;
	}
 


}
